﻿using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

using System.Collections;
using System.Collections.Generic;

namespace Code.UI
{
    public class SkillGUI:MonoBehaviour,IPointerClickHandler
    {
        private SkillConfigDialog _skillConfigDialog;

        [SerializeField] private TMP_Text _levelText;
        [SerializeField] private Image _img;
        [SerializeField] private TMP_Text _moneyText;
        
        private Skill _currentSkill;

        private UIPlayer _player;

        public void Init(Skill skill, Transform skillConfigDialog) 
        {
            _currentSkill = skill;
            _levelText.text ="Level "+ skill.Level.ToString();
            _img.sprite = skill.Img;
            _moneyText.text = skill.Money.ToString();
            _skillConfigDialog = skillConfigDialog.GetComponent<SkillConfigDialog>();
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            StopAllCoroutines();
            _skillConfigDialog.gameObject.SetActive(true);
            _skillConfigDialog.Init(_currentSkill);
            
            StartCoroutine(SkillConfigCoro());
        }

        private IEnumerator SkillConfigCoro()
        {
            while (true) 
            {
                yield return null;
                if (Input.GetMouseButtonDown(0))
                {
                    EventSystem eventSystem = EventSystem.current;
                    PointerEventData pointerEventData = new PointerEventData(eventSystem);
                    pointerEventData.position = Input.mousePosition;
                    //射线检测ui
                    List<RaycastResult> uiRaycastResultCache = new List<RaycastResult>();
                    eventSystem.RaycastAll(pointerEventData, uiRaycastResultCache);
                    if (uiRaycastResultCache.Count > 0) 
                    {
                        Debug.Log(uiRaycastResultCache[0].gameObject.name);
                        if (uiRaycastResultCache[0].gameObject.name == "SkillSlot")
                        {
                            var skillSlot= uiRaycastResultCache[0].gameObject.GetComponent<SkillSlot>();
                            skillSlot.Init(_currentSkill,_skillConfigDialog.Player);
                            //break;
                        }
                    }
                    else 
                    {
                        //StopAllCoroutines();
                        //break;
                    }

                }
                        
                
                
            }
        }
    }
}
